package com.zhou.org.common;

import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.zhou.framework.util.SettingUtil;
import com.zhou.framework.exception.LoginException;
import lombok.extern.slf4j.Slf4j;

import java.util.regex.Pattern;

/**
 * @author lang.zhou
 * @since 2023/2/26
 */
@Slf4j
public class PasswordUtil {
    private static final Pattern NUMBER_PATTERN = Pattern.compile(".*[0-9].*");
    private static final Pattern LETTER_PATTERN = Pattern.compile(".*[a-zA-z].*");
    private static final Pattern MARK_PATTERN = Pattern.compile(".*[~!@#$%^&*()_+|<>,.?/:;'\\[\\]{}\"]+.*");

    public static String decrypt(String password){
        String priKey = SettingUtil.getString("system", "pri_key","");
        return decrypt(password,priKey);
    }

    public static String decrypt(String password, String pri){
        try{
            // 初始化RSA工具并设置私钥
            RSA priRsa = new RSA(pri,null);
            return priRsa.decryptStr(password, KeyType.PrivateKey);
        }catch (Exception e){
            log.error("解密失败：{}",e.getMessage());
            throw new LoginException("用户名或密码错误");
        }
    }

    public static String encrypt(String password, String pri){
        try{
            // 公钥加密
            RSA priRsa = new RSA(pri,null);
            return priRsa.encryptHex(password, KeyType.PrivateKey);
        }catch (Exception e){
            log.error("加密失败：{}",e.getMessage());
            throw new LoginException("加密错误");
        }
    }

    public static int getPasswordStronger(String pwd){
        int n = 0;
        if(NUMBER_PATTERN.matcher(pwd).matches()){
            ++ n;
        }
        if(LETTER_PATTERN.matcher(pwd).matches()){
            ++ n;
        }
        if(MARK_PATTERN.matcher(pwd).matches()){
            ++ n;
        }
        return n;
    }
}
